package de.hypoport.einarbeitung.scrumspirit.helper;

import java.net.MalformedURLException;
import java.net.URL;

import org.junit.rules.ExternalResource;

import com.google.code.joliratools.jolirium.Jolirium;
import com.google.code.joliratools.jolirium.JoliriumServer;


/**
 * Überprüft ob ein Selenium Server gestartet ist
 * und falls nicht wird einer gestartet
 */
public class SeleniumTestRunner extends ExternalResource {

	private static Integer seleniumPort;

	private static JoliriumServer server = null;
	private static String seleniumHost;
	private static URL url;
	private final boolean externalServerRunning = false;
	private Thread seleniumServerThread;
	private Jolirium seleniumClient;
	private final String webAppPath;

	private static final Integer SELENIUM_SEFAULT_PORT = 4444;
  private static final String SELENIUM_SEFAULT_HOST ="localhost";
	private static final String SELENIUM_SEFAULT_BROWSER = "*firefox";
	private static final String FIREFOX_PROFILE = "C:/entwicklung/Scrum-Spirit/Scrum-Spirit/src/test/resources/selenium/ffprofile";
	/**
	 * Sekunden
	 */
	private static final int SELENIUM_DEFAULT_SERVERSTART_TIMEOUT = 10;

	public SeleniumTestRunner(Integer seleniumPort, String seleniumHost, String webAppPath) {
		SeleniumTestRunner.seleniumPort = seleniumPort;
		SeleniumTestRunner.seleniumHost = seleniumHost;
		this.webAppPath = webAppPath;
  }

	public SeleniumTestRunner(Integer seleniumPort, String webAppPath)
  {
		this(seleniumPort, SELENIUM_SEFAULT_HOST, webAppPath);
  }


	public SeleniumTestRunner(String webAppPath)
  {
		this(SELENIUM_SEFAULT_PORT, SELENIUM_SEFAULT_HOST, webAppPath);
  }


	public String getWebAppPath() {
		return webAppPath;
	}

	@Override
	protected void before() throws Throwable {

		seleniumClient = createServer().getJolirium();


	}

	private static synchronized JoliriumServer createServer() {
		if (server != null) {
			return server;
		}

		if (null == url) {
			url = createUrl();

		}

		return server = new JoliriumServer(SELENIUM_SEFAULT_BROWSER, null, url);
	}

	private static URL createUrl() {
		try {
			return new URL("http://" + seleniumHost + ':' + seleniumPort.toString());
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		}

	}

	@Override
	protected void after() {

		if (null != seleniumClient) {
			seleniumClient.close();
		}

	}

	public Integer getSeleniumPort() {
		return seleniumPort;
	}

	public String getSeleniumHost() {
		return seleniumHost;
	}

	public boolean isExternalServerRunning() {
		return externalServerRunning;
	}

	public Thread getSeleniumServerThread() {
		return seleniumServerThread;
	}

	public Jolirium getSeleniumClient() {
		return seleniumClient;
	}

}
